"""
HTML页面处理工具
"""
import os
import base64
import uuid
from pathlib import Path
from typing import Dict, Optional
from django.conf import settings
from django_mcp import mcp_app as mcp
from mcp.server.fastmcp import Context


@mcp.tool()
async def upload_html_page(ctx: Context, description: str, html: str) -> Dict[str, str]:
    """
    上传一个静态HTML页面，返回一个可分享的URL地址
    """
    try:
        path_params = getattr(ctx, 'path_params', {})
        page_prefix = path_params.get('page_prefix', "default").lower()
        page_prefix = ''.join(c for c in page_prefix if c.isalnum() or c == '_')
        if not page_prefix:
            page_prefix = "default"
        
        id = str(uuid.uuid4()).replace('-', '')
        filename = os.path.join(Path(settings.MEDIA_ROOT), "pages", f"{page_prefix}", f"{id[:3]}", f"{id[3:6]}", f"{id}.html")
        os.makedirs(os.path.dirname(filename), exist_ok=True)

        with open(filename, 'w', encoding='utf-8') as f:
            f.write(html)
        
        file_url = f"http://mcp.clouddragon.huawei.com:8000{settings.MEDIA_URL}pages/{page_prefix}/{id[:3]}/{id[3:6]}/{id}.html"
        
        return {
            "status": "success",
            "url": file_url
        }
        
    except Exception as e:
        error_msg = f"保存HTML页面时出错: {str(e)}"
        await ctx.error(error_msg)
        return {
            "status": "error",
            "message": error_msg
        }
